#include "SDL.h"
#include "Timer.h"
#include "Error.h"
#include "Log.h"
#include "StringUtility.h"

namespace Engine
{
	Timer::Timer():m_dt(0.0f), m_dtCap(0.0f), m_oldTicks(0), m_paused(false){}

	bool Timer::Initialize(float dtCap)
	{  
		m_dtCap = dtCap;

		Log("****Initializing Timer****");

		if(SDL_InitSubSystem(SDL_INIT_TIMER) == -1)
		{ 
			Error("Unable to initialize Timer");
			return false;
		}

		Log("dt cap:" + ToString(dtCap) + "s");
		Log("Timer initialiazed");
		Log(" ");

		m_oldTicks = SDL_GetTicks();
		return true;
	}

	bool Timer::Initialize(rapidxml::xml_node <>* node)
	{
		if(!node ->first_node("DTCap"))
		{
			Error("DTCap not found in config file");
			return false;
		}
		float dt;
		if(!FromString(dt, node ->first_node("DTCap") ->value()))
		{
			Error("Error parsing DTCap from config file");
			return false;
		}

		return Initialize(dt);
	}

	void Timer::Pause()
	{
		m_paused = true;
	}

	bool Timer::IsPaused() const
	{
		return m_paused;
	}

	void Timer::Unpause()
	{
		m_paused = false;
		m_oldTicks = SDL_GetTicks();
	}

	void Timer::Update()
	{
		if(!m_paused)
		{
			unsigned int newTicks = SDL_GetTicks();

			m_dt = static_cast <float> (newTicks - m_oldTicks);
			m_dt *= 0.001f;//sets dt from milliseconds to seconds

			if(m_dt > m_dtCap)
				m_dt = m_dtCap;

			m_oldTicks = newTicks;
		}
		else m_dt = 0.0f;
	}

	float Timer::GetDT() const
	{
		return m_dt;
	}
}


